package com.zmx.patientend.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CaseManagementActivity extends BaseActivity {


    @BindView(R.id.now_medical_history)
    TextView nowMedicalHistory;
    @BindView(R.id.past_medical_history)
    TextView pastMedicalHistory;
    @BindView(R.id.genetic)
    TextView genetic;
    @BindView(R.id.allergy)
    TextView allergy;
    @BindView(R.id.the_diagnosis)
    TextView theDiagnosis;
    @BindView(R.id.regular)
    TextView regular;
    @BindView(R.id.notice)
    TextView notice;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.main_suit)
    TextView mainSuit;

    private String medical_id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_case_management;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        medical_id = this.getIntent().getStringExtra("medical_id");
        getMedicalUserList();

    }

    @OnClick(R.id.submit)
    public void onViewClicked() {

        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示：");
        builder.setMessage("确定保存本地？");

        //设置确定按钮
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取图片某布局
                View view= findViewById(R.id.layout);
                save(view);
            }
        });
        //设置取消按钮
        builder.setPositiveButton("取消",null);
        //显示提示框
        builder.show();


    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        JSONObject data = object.getJSONObject("data");
                        mainSuit.setText(data.getString("sketch"));
                        nowMedicalHistory.setText(data.getString("now"));
                        pastMedicalHistory.setText(data.getString("history"));
                        genetic.setText(data.getString("family"));
                        allergy.setText(data.getString("allergy"));
                        regular.setText(data.getString("marry"));
                        notice.setText(data.getString("birthday"));
                        theDiagnosis.setText(data.getString("disease_name"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }

    };

    public void getMedicalUserList() {

        List<String> ls = new ArrayList<>();
        ls.add(medical_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getMedical");
        params.put("data[medical_id]", medical_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.medical/entry", params, handler, 1, 404);

    }

    //传入要保存的view
    public void save(View view) {
        int w = view.getWidth();
        int h = view.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        view.layout(0, 0, w, h);
        view.draw(c);
        // 缩小图片
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例
        bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        saveBitmap(bmp, format.format(new Date()) + ".JPEG");
    }

    private void saveBitmap(Bitmap bitmap, String bitName) {
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在常用相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
                // 插入图库
                MediaStore.Images.Media.insertImage(mActivity.getContentResolver(), file.getAbsolutePath(), bitName, null);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        mActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        Toast("保存成功");
    }

}
